<template>
    <div class="container">
        <el-form label-width="auto" size="large" :model="loginForm" style="flex: 1 1" :rules="rules" ref="formIns">
            <el-form-item label="账号" prop="username">
                <el-input v-model="loginForm.username" placeholder="请输入账号" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>

            <el-form-item class="register">
                <el-link @click="register">注册账号</el-link>
                <span style="margin: 0 8px;">或者</span>
                <el-link type="primary" @click="toIndex">游客模式</el-link>
            </el-form-item>
            <el-form-item class="login">
                <el-button style="flex: 1 1" type="primary" @click="handleLogin">登录</el-button>
            </el-form-item>
            <el-form-item class="login">
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { set } from "../../util/localStorage"

import type { FormRules, FormInstance } from "element-plus"
import axios from "axios"

const formIns = ref<FormInstance>();
const router = useRouter()

const loginForm = reactive({
    username: '',
    password: ''
})


const rules = ref<FormRules>({
    username: [
        { required: true, message: "需要填写用户名" },
        { max: 8, message: "最多八位" },
    ],
    password: [
        { required: true, message: "需要填写密码" },
        { max: 8, message: "最多八位" },
    ],
});

const register = () => {
    router.push("/register")
}

const toIndex = () => {
    router.push("index")
}

const handleLogin = async () => {
    const is = await formIns.value?.validate()
    if (is) {
        const loginRes = await axios.post("/api/login", loginForm)
        if (loginRes.data.message) {
            ElMessage.error({
                message: loginRes.data.message
            })
            return
        }
        set("user", loginRes.data)
        const perRes = await axios.get("/api/getPer", { params: { per: loginRes.data.permissions } })
        set("per", perRes.data)
        toIndex()
    }
}

</script>

<style scoped>
.container {
    width: 400px;
    height: 100vh;
    margin: auto;
    display: flex;
    align-items: center;
    position: relative;
}

.register :deep(.el-form-item__content) {
    justify-content: end;
}

.login :deep(.el-form-item__content) {
    justify-content: center;
}
</style>